package com.xcity.game.equip;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;

import com.alibaba.fastjson.JSON;
import com.xcity.db.entity.Player;
import com.xcity.pomelo.push.SyncPush;
import com.xcity.pomelo.push.sync.CustomSync;
import com.xcity.pomelo.push.sync.LongSync;
import com.xcity.pomelo.response.EquipmentBagResponse;

public class Equipments {

	protected Player owner;
	protected List<Equip> equipments;
	
	public static final int DEFAULT_CAPACITY = 500;
	protected static final Logger LOG = EquipmentService.LOG;
	
	public Equipments(Player player, List<Equip> equipments) {
		this.owner = player;
		this.equipments = equipments != null ? equipments : new ArrayList<Equip>();
		for (int i = 0; i < this.equipments.size(); i++) {
			this.equipments.get(i).vm = this;
		}
	}

	public Player getOwner() {
		return owner;
	}

	public void setOwner(Player owner) {
		this.owner = owner;
	}

	public List<Equip> getEquipments() {
		return equipments;
	}
	
	public Equip getEquip(long id) {
		List<Equip> list = equipments;
		for (int i = list.size() - 1; i >= 0; i--) {
			Equip equip = list.get(i);
			if (id == equip.getId()) {
				return equip;
			}
		}
		return null;
	}
	
	public Equip removeEquip(long id, String cause) {
		List<Equip> list = equipments;
		for (int i = list.size() - 1; i >= 0; i--) {
			Equip equip = list.get(i);
			if (id == equip.getId()) {
				list.remove(equip);
				equipRemoved(equip);
				LOG.info("[EQUIP REMOVE]ID[{}]EQUIP[{}]CAUSE[{}]", getOwner().getId(), id, cause);
				return equip;
			}
		}
		return null;
	}
	
	public void removeEquip(Equip equip, String cause) {
		if (equipments.remove(equip)) {
			equipRemoved(equip);
			LOG.info("[EQUIP REMOVE]ID[{}]EQUIP[{}]TID[{}]DTID[{}]CAUSE[{}]", getOwner().getId(), equip.getId(), equip.getTemplateId(), equip.getDataTemplateId(), cause);
		}
	}
	
	public void addEquip(Equip equip, String cause) {
		equip.vm = this;
		equipments.add(equip);
		equipAdded(equip);
		LOG.info("[EQUIP ADD]ID[{}]EQUIP[{}]TID[{}]DTID[{}]CAUSE[{}]", getOwner().getId(), equip.getId(), equip.getTemplateId(), equip.getDataTemplateId(), cause);
	}
	
	public int size() {
		return equipments.size();
	}
	
	public void equipAdded(Equip equip) {
		getOwner().send(new CustomSync(SyncPush.SYNC_EQUIP_ADDED, new EquipmentBagResponse.Equipment(equip)));
	}
	
	public void equipRemoved(Equip equip) {
		getOwner().send(new LongSync(SyncPush.SYNC_EQUIP_REMOVED, equip.getId()));
	}

	@Override
	public String toString() {
		return JSON.toJSONString(equipments);
	}
	
}
